<?php

namespace app\admin\controller;


use app\admin\model\SystemAdmin;
use app\admin\model\SystemFinanceDay;
use app\admin\model\SystemQuick;
use app\common\controller\AdminController;
use think\App;
use think\facade\Db;
use think\facade\Env;

class Index extends AdminController
{

    /**
     * 后台主页
     * @return string
     * @throws \Exception
     */
    public function index()
    {
        return $this->fetch('', [
            'admin' => session('admin'),
        ]);
    }

    /**
     * 后台统计报表数据组装
     * @return array|false|string
     * @throws \Exception
     */
    public function setEchartsData()
    {
        $x_line_data_original = SystemFinanceDay::column('date');
        $x_line_data = [];
        foreach ($x_line_data_original as $item) {
            $x_line_data[] = date('m.d', $item);
        }
        $line_title = ['消费总金额', '退款金额', '代金券'];
        $recharge_data = SystemFinanceDay::column('user_consume');
        $refund_data = SystemFinanceDay::column('user_refund');
        $order_data = SystemFinanceDay::column('cashcard_use');
        $y_line_data_original = [
            '消费总金额' => $recharge_data,
            '退款金额' => $refund_data,
            '代金券金额' => $order_data
        ];
        foreach ($y_line_data_original as $k => $v) {
            $y_data = [
                'name' => $k,
                'type' => 'line',
//                'stack' => '总量',
                'data' => $v,
            ];
            $y_line_data[] = $y_data;
        }
        $line_color = ['#a20a0a', '#21209c', '#fdb827'];
        $data = [
            'text_title' => '收支统计',
            'line_title' => $line_title,
            'x_line_data' => $x_line_data,
            'y_line_data' => $y_line_data,
            'line_color' => $line_color,
        ];
        $this->assign('echarts_data', $data);
        return json_encode($data, true);
    }

    /**
     * 统计数据处理
     * @return \think\response\Json
     */
    public function countData()
    {
        $user_count = Db::name('user_base')->where([])->count();
//        $product_count = Db::table($prefix . 'product_base')->where([])->count();
//        $order_count = Db::table($prefix . 'product_order')->where([])->count();
        $order_count = Db::name('user_order')->where([])->count();
        $store_count = Db::name('shop_store')->where([])->count();
        $cashcard_count = Db::name('user_order')->where([])->sum('cashcard_dec');
//        $recharge_count = Db::table($prefix . 'system_finance_day')->where([])->sum('user_recharge');
//        $recharge_count = Db::table($prefix . 'user_recharge')->where([])->sum('money');
//        $agent_count = Db::table($prefix.'system_admin')->where('pid','>','0')->count();
        $data = [
            'user_count' => $user_count,
            'store_count' => $store_count,
//            'product_count' => $product_count,
            'order_count' => $order_count,
            'cashcard_count' => $cashcard_count,
//            'agent_count'   => $agent_count,
        ];
        if ($this->request->isAjax()) {
            return json($data);
        }
        $this->assign('count_data', $data);
    }


    /**
     * 后台欢迎页
     * @return string
     * @throws \Exception
     */
    public function welcome()
    {
        //首页图表获取
        $echarts_data = $this->setEchartsData();
//        $this->assign('admin_id',session('admin'));
        //首页数据获取
        $this->countData();
        //快捷菜单获取
        $quicks = SystemQuick::field('id,title,icon,href')
            ->where(['status' => 1])
            ->order('sort', 'desc')
            ->limit(8)
            ->select();
        $this->assign('quicks', $quicks);
        return $this->fetch();
    }

    /**
     * 修改管理员信息
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editAdmin()
    {
        $id = session('admin.id');
        $row = (new SystemAdmin())
            ->withoutField('password')
            ->find($id);
        empty($row) && $this->error('用户信息不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $this->isDemo && $this->error('演示环境下不允许修改');
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $row
                    ->allowField(['head_img', 'phone', 'remark', 'update_time'])
                    ->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * 修改密码
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editPassword()
    {
        $id = session('admin.id');
        $row = (new SystemAdmin())
            ->withoutField('password')
            ->find($id);
        if (!$row) {
            $this->error('用户信息不存在');
        }
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $this->isDemo && $this->error('演示环境下不允许修改');
            $rule = [
                'password|登录密码' => 'require',
                'password_again|确认密码' => 'require',
            ];
            $this->validate($post, $rule);
            if ($post['password'] != $post['password_again']) {
                $this->error('两次密码输入不一致');
            }

            // 判断是否为演示站点
            $example = Env::get('admin.example', 0);
            $example == 1 && $this->error('演示站点不允许修改密码');

            try {
                $save = $row->save([
                    'password' => password($post['password']),
                ]);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            if ($save) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }
        $this->assign('row', $row);
        return $this->fetch();
    }


}
